package org.jader.bolao.gui.swing.table;

import javax.swing.table.DefaultTableModel;

import org.jader.bolao.GamePlayer;


public class PlayerPointsTableModel extends DefaultTableModel {
	private static final long serialVersionUID = 1L;
	
	private final int COLUMN_COUNT = 4*6 + 5;
	
	private GamePlayer currentPlayer = null;
	
	public void showGamePlayer(GamePlayer arg0) {
		this.currentPlayer = arg0;
	}
	
	@Override
    public String getColumnName(int col) {
    	if (col == COLUMN_COUNT-1) return "Total";
    	if (col%7 == 0) return "E";
    	if (col%7 == 6) return "Soma";
        return Integer.toString(col%7);
    }
    
	@Override
	public int getColumnCount() {
		return COLUMN_COUNT;
	}

	@Override
	public int getRowCount() {
		return 1;
	}

    @SuppressWarnings("unchecked")
	public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }
    
	@Override
	public Object getValueAt(int row, int col) {
		if (col%7 == 6) {
			int sum = 0;
			for (int i=5; i>0; i--)
				sum += (Integer)getValueAt(row, col-i);
			return new Integer(sum);
		}
		if (col == COLUMN_COUNT-1) {
			if (currentPlayer == null) return 0;
			return currentPlayer.getSum();
		}
		// Get points from selected player on gamePlayersTable
		if (currentPlayer == null || !currentPlayer.isDetailed()) return 0;
		return new Integer(currentPlayer.getBalls()[col2ball(col)]);
	}

    public boolean isCellEditable(int row, int col){
    	if (col %7 == 6 || col == COLUMN_COUNT-1) return false;
    	return true;
    }
    
	public void setValueAt(Object value, int row, int col) {
		currentPlayer.setBall(col2ball(col), (Integer)value);
        fireTableCellUpdated(row, col);
    }
	
	private int col2ball(int col) {
		if (col<7) return col;
		if (col<14) return col-1;
		if (col<21) return col-2;
		return col-3;
	}
}
